package com.kun.demo04_synchronize.solution;


import com.kun.demo04_synchronize.probelm.NotSafeCase1_buyTickets;
import org.junit.Test;

import java.util.concurrent.locks.ReentrantLock;

//测试Lock锁
public class TestLock {

    private int tickets = 10;

    private ReentrantLock lock = new ReentrantLock();

    class Ticket implements Runnable {


        @Override
        public void run() {
            while (true){
                lock.lock();
                try {
                    if (tickets <= 0){
                        break;
                    }
                    Thread.sleep(100);
                    System.out.println(Thread.currentThread().getName() + " : " + tickets--);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }

            }
        }
    }

    @Test
    public void testLock() throws InterruptedException {
        System.out.println("开始买票...");
        Ticket ticket = new Ticket();
        new Thread(ticket, "A").start();
        new Thread(ticket, "B").start();
        new Thread(ticket, "C").start();
        Thread.sleep(2000); // 延迟主线程退出
    }


}
